<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <el-tab-pane v-loading="loading" label="角色管理">
            <!-- 新增按钮 -->
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="showDialog = true"
            >新增角色</el-button>
            <el-table :data="list" style="width: 100%">
              <el-table-column
                label="序号"
                type="index"
                :index="indexMethod"
                width="100"
                align="center"
              />
              <el-table-column label="角色名称" prop="name" align="center" />
              <el-table-column label="描述" prop="description" align="center" />
              <el-table-column label="操作" width="360" align="center">
                <!-- 根据我们要用数据所有用插槽渲染才能拿到ID -->
                <template v-slot="{ row }">
                  <el-button type="success" size="small" @click="showQX(row.id)">分配权限</el-button>
                  <el-button type="primary" size="small" @click="showEdit(row)">修改</el-button>
                  <el-button type="danger" size="small" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分配权限的弹层 -->
            <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog">
              <el-tree
                ref="tree"
                v-loading="treeLoading"
                :data="permissionData"
                :props="{ label: 'name' }"
                :default-expand-all="true"
                :show-checkbox="true"
                :check-strictly="true"
                node-key="id"
              />
              <template #footer>
                <div style="text-align: right;">
                  <el-button @click="closeAssignDialog">取消</el-button>
                  <el-button type="primary" @click="clickAssign">确定</el-button>
                </div>
              </template>
            </el-dialog>
            <el-row type="flex" justify="end" style="margin-top: 10px;">
              <!--
                background:分页带有背景
                total： 总共有多少条数据
                page-size: 每页显示多少条
                current-page: 当前页
                -->
              <el-pagination
                layout="prev, pager, next"
                background
                :total="total"
                :page-size="pagesize"
                :current-page="page"
                @current-change="changeFn"
              />
            </el-row>
            <!-- 新增角色弹窗 -->
            <el-dialog
              :title="form.id ? '修改角色' : '新增角色' "
              :visible="showDialog"
              width="30%"
              @close="close"
            >
              <el-form ref="form" :model="form" label-width="80px" :rules="rules">
                <el-form-item label="角色名称" prop="name">
                  <el-input v-model.trim="form.name" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                  <el-input v-model.trim="form.description" placeholder="请输入角色描述" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="close">取 消</el-button>
                <el-button type="primary" @click="add">确 定</el-button>
              </template>
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="company">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
// 1.进来就先发请求渲染列表
import { mapState } from 'vuex'
import { getCompanyById } from '@/api/user'
import { getRoleList, delRole, addRole, updateRole, getRoleDetail, AssignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { listToTree } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'role',
      list: [], // 存放角色列表
      total: 0,
      pagesize: 10,
      page: 1,
      loading: false,
      showAssignDialog: false, // 控制权限弹层的显示隐藏
      roleId: '', // 记录正在操作的角色
      permissionData: [], // 存储权限数据
      treeLoading: false, // 权限弹窗的加载效果
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      showDialog: false,
      companyForm: {}
    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  created() {
    this.getRoleList() // 获取角色列表
    this.getCompanyInfo()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const data = await getRoleList(this.page, this.pagesize)
      // console.log(data)
      this.list = data.rows
      this.total = data.total
      this.loading = false
    },
    changeFn(value) {
      // 监视页码变化,修改当前页
      this.page = value
      // 重新发请求
      this.getRoleList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    async del(id) {
      try {
        await this.$confirm('亲，确定要删除该角色吗?', '温馨提示', { type: 'warning' })
      } catch { return }
      // 发送请求，删除角色
      await delRole(id)
      this.$message.success('删除角色成功')
      // 重新渲染
      if (this.list.length === 1) {
        // 当前页面只有一条数据了
        this.page--
      }
      this.getRoleList()
    },
    close() {
      this.showDialog = false
      // 重置表单数据
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    async add() {
      try {
        await this.$refs.form.validate()
      } catch {
        return false
      }
      // 发送请求
      if (this.form.id) {
        await updateRole(this.form)
      } else {
        await addRole(this.form)
        // 把page改为最后一页 30
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
      }
      // 提示消息
      this.$message.success('操作成功')
      // 重新渲染
      this.getRoleList()
      // 关闭弹窗
      this.showDialog = false
    },
    showEdit(row) {
      this.showDialog = true
      this.form = { ...row }
    },
    async getCompanyInfo() {
      const data = await getCompanyById(this.userInfo.companyId)
      // console.log(data)
      this.companyForm = data
    },
    async showQX(id) {
      this.treeLoading = true
      this.roleId = id
      this.showAssignDialog = true
      const data = await getPermissionList()
      this.permissionData = listToTree(data, '0')
      const data1 = await getRoleDetail(this.roleId)
      this.$refs.tree.setCheckedKeys(data1.permIds)
      this.treeLoading = false
    },
    //  点击确定按钮分配权限
    async clickAssign() {
      await AssignPerm({
        id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('分配成功')
      this.showAssignDialog = false
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    }
  }
}
</script>

<style>

</style>
